package com.yixq.soa.service.web.auth;

import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yixq.soa.service.web.annotation.Permission;
import com.yixq.soa.service.web.utils.EnvironmentUtils;
import com.google.common.collect.Sets;

public class DoorduAuthInterceptor implements HandlerInterceptor {
	
	Logger log = LoggerFactory.getLogger(DoorduAuthInterceptor.class);
	
	public void addAuthToList(String[] ps,Set<String> list){
		if(ps == null){
			return;
		}
		for(String p:ps){
			if(StringUtils.isNotBlank(p)){
				String[] pss = p.trim().split(",");
				for (String str : pss) {
					if(StringUtils.isNoneBlank(str)){
						list.add(str.trim());
					}
				}
			}
		}
		
	}
	

	@SuppressWarnings("unused")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//builder.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL);
//		String accept = request.getHeader("Accept");
//		if("*/*".equals(accept)){
//			
//		}
		//System.out.println(accept);
		
		
		if(handler instanceof HandlerMethod){
			HandlerMethod hm = (HandlerMethod) handler;
			Permission t_permission = AnnotationUtils.findAnnotation(hm.getBeanType(), Permission.class);
			Permission m_permission = AnnotationUtils.findAnnotation(hm.getMethod(), Permission.class);
			Set<String> plist = Sets.newHashSet();
			boolean needLogin = false;
			
			boolean allowVisitor = false;
			
			if(t_permission != null){
				addAuthToList(t_permission.value(),plist);
				allowVisitor = t_permission.allowVisitor();
				needLogin = true;
			}
			if(m_permission != null){
				addAuthToList(m_permission.value(),plist);
				allowVisitor = m_permission.allowVisitor();
				needLogin = true;
			}
			

			if(!needLogin && plist.isEmpty()){
				return true;
			}else{
				HttpSession session = request.getSession(false);
				
				if(session == null){
					RequestDispatcher dispatcher = request.getRequestDispatcher("/error/nologin");
					dispatcher.forward(request, response);
					return false;
				}
				
				UserRealm userRealm = (UserRealm)session.getAttribute(UserRealm.USER_REALM_KEY);
				
				if(userRealm == null){
					RequestDispatcher dispatcher = request.getRequestDispatcher("/error/nologin");
					dispatcher.forward(request, response);
					return false;
				}
				
				if(plist.isEmpty()){//如果鉴权是空的.而且已经登录.则允许访问.
					return true;
				}
				
				String profile = EnvironmentUtils.getActiveProfile();
				if(!"prod".equals(profile)){//非正式环境下用于测试权限使用.
					List<String> ps = userRealm.getPermissions();
					if(ps != null && ps.size() == 1 && "MOCK_SUPER_".equals(ps.get(0))){
						log.info(profile+"环境下.使用 mock User 跳过鉴权."+StringUtils.join(plist,","));
						return true;
					}
				}
				
				if(userRealm.getPermissions().containsAll(plist)){
					return true;
				}
				
				RequestDispatcher dispatcher = request.getRequestDispatcher("/error/403");
				dispatcher.forward(request, response);
				return false;
			}
			
		}
		
		log.info("!!Un Authed request:"+handler);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
